<template>
    <el-dialog v-model="showDialog" :title="form.path ? '修改企业' : '新增企业'" width="500" @close="close">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="auto" v-loading="loading">
                     <el-form-item label="企业名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入企业名称" />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="doClose" :loading="loading">取消</el-button>
                <el-button type="primary" @click="preSave" :loading="loading">确定</el-button>
            </div>
        </template>

    </el-dialog>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'

interface RuleForm {
    name: string | null
    path: string | null
}

const emits = defineEmits(["close"]);

const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
    editData: {
        default: {}
    }
});


const showDialog = ref<boolean>(false)
const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const rules = ref({
    name:[{required: true, message: '请输入企业名称', trigger: 'blur'}]
})
const form = ref<RuleForm>({
    name: null,
    path: null
})


watch(() => props.show, (value) => {
    if (value !== showDialog.value) {
        showDialog.value = value
    }
    initData()
}, {deep: true})

function initData() {
    let editData:any = {...props.editData || {}}
    if (formRef.value) {
        formRef.value.resetFields()
    }
    form.value = editData
}
function close() {
    emits("close")
}

function doClose() {
    showDialog.value = false
}
function preSave() {
    if (!formRef.value) {
        return
    }
    formRef.value.validate((valid, fields) => {
    if (valid) {
      doSave()
    }
  })
}
async function doSave () {
    let data:any = {...form.value || {}}
    let editData:any = {...props.editData || {}}
    let path = editData.path
    let name = data.name
    if (path) {
        const result = await window.electronAPI.renameFolder(path, name);
        if (result.success) {
            ElMessage.success("修改成功")
            doClose()
        } else {
            ElMessage.error("修改失败")
        }
    } else {
        let parentPath = editData.parentPath
        const result = await window.electronAPI.createFolder(parentPath, name);
        if (result.success) {
            ElMessage.success("创建成功")
            doClose()
        } else {
            ElMessage.error("创建失败")
        }

    }
    // const result = await window.electronAPI.renameFolder(companyPath);
}
</script>
<style lang="scss" scoped>
</style>